var searchInputKeyupTimeout,
	isSlideUp = false;

initStorage(function () {
	['stroke', 'dblclick'].forEach(function (key) {
		var classList = document.querySelector('#switches>.' + key).classList;
		if (window.getTextMethod[key]) {
			classList.add('active');
		} else {
			classList.remove('active');
		}
	});
});


var switches = document.querySelector('#switches'),
	strokeSwitch = switches.querySelector('.stroke'),
	dblclickSwitch = switches.querySelector('.dblclick');

switches.addEventListener('click', function (event) {
	event.target.classList.toggle('active');
	['stroke', 'dblclick'].forEach(function (key) {
		if (event.target.classList.contains(key)) {
			if (event.target.classList.contains('active')) {
				window.getTextMethod[key] = true;
			} else {
				window.getTextMethod[key] = false;
			}
			chrome.storage.local.set({'getTextMethod': window.getTextMethod});
		}
	});
});


document.querySelector('#search>input[type=text]').addEventListener('keyup', function (event) {
	var inputElement = document.querySelector('#search>input[type=text]'),
		yourDictMain = document.querySelector('#result');
		
	function doSearch() {
		var resultDiv = document.getElementById('result');
		if (isSlideUp) {
			resultDiv.style.top = '250px';
			animate(resultDiv, {top: '0px'}, 400);
		}
		yourDictMain.textContent = '正在查询中...';

		httpRequest('https://dict.youdao.com/fsearch?q=' + encodeURIComponent(inputElement.value.trim()) +
					'&xmlVersion=3.2&pos=-1&scrfrom=stroke', 'xml')
			.then(parseYodaoXml)
			.then(function (parsedObj) {
				yourDictMain.innerHTML = parsedObj.parsedHTML;
				getYodaoSpeech(parsedObj, yourDictMain);
				if (!isSlideUp) {
					var idleDivInner = document.querySelectorAll('#idle>*');
					for(var i = 0; i < idleDivInner.length; i++){
						var elementTop = parseFloat(getComputedStyle(idleDivInner[i])['top']);
						animate(idleDivInner[i], {top: (elementTop - 246) + 'px', opacity: 0}, 400);
					}
					var idleDiv = document.getElementById('idle');
					animate(idleDiv, {height: '0px'}, 400, function () {
						idleDiv.style.display = 'none';
					});
					resultDiv.style.display = 'block';
					isSlideUp = true;
				}
			})
			.catch(function (error) {
				console.error(error);
			});
	}
	
	if (!(event.keyCode === 13 ||
		 event.keyCode === 32 ||
		 event.keyCode === 45 ||
		 (event.keyCode >= 65 && event.keyCode <= 90))
			) {
		return;
	} else {
		clearTimeout(searchInputKeyupTimeout);
	}
	
	if (inputElement.value && event.keyCode === 13) {
		doSearch();
	} else {
		searchInputKeyupTimeout = setTimeout(function () {
			doSearch();
		}, 600);
	}
	
});